package com.velvetantler.weather.view.detail

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import com.qweather.sdk.response.weather.WeatherDailyResponse
import com.velvetantler.weather.R
import com.velvetantler.weather.WeatherGlobal
import com.velvetantler.weather.base.BaseBindingActivity
import com.velvetantler.weather.bean.CityInfo
import com.velvetantler.weather.bean.CityStar
import com.velvetantler.weather.databinding.AcWeatherDetailBinding
import com.velvetantler.weather.utils.CityStarUtils

class WeatherDetailActivity : BaseBindingActivity<AcWeatherDetailBinding>(), WeatherDetailView {

    private lateinit var presenter: WeatherDetailPresenter

    private var isStar: Boolean = false

    private var currentCity: CityInfo? = null

    private var cityStar: CityStar? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        initView()
    }

    override fun initBinding(layoutInflater: LayoutInflater): AcWeatherDetailBinding {
        return AcWeatherDetailBinding.inflate(layoutInflater)
    }

    fun initView() {
        // 绑定城市名称
        val cityName = intent.getStringExtra("cityName") ?: WeatherGlobal.getCityName()
        binding.detailTodayCard.tvCityName.text = cityName
        // 接收首页传递的经纬度参数
        val longitude = intent.getStringExtra("longitude") ?: WeatherGlobal.getLongitude()
        val latitude = intent.getStringExtra("latitude") ?: WeatherGlobal.getLatitude()
        currentCity = CityInfo(cityName, "", latitude.toDouble(), longitude.toDouble())
        // 初始化Presenter
        presenter = WeatherDetailPresenter(this, WeatherDetailModel())
        // 请求天气数据
        presenter.requestWeather3dayData(longitude, latitude)
        // 视频按钮点击事件
        binding.detailTodayCard.ivVideoIcon.setOnClickListener {
            val intent = Intent(this, Media3PlayerActivity::class.java)
            startActivity(intent)
        }
        // 收藏图标初始化，todo 从首选项读
        initCityStar()
    }

    @SuppressLint("SetTextI18n")
    override fun getWeather3dayDataSucceed(response: WeatherDailyResponse) {
        val weatherDaily = response.daily[0]
        cityStar = CityStar(
            currentCity!!.cityName,
            currentCity!!.latitude,
            currentCity!!.longitude,
            weatherDaily.tempMin,
            weatherDaily.tempMax
        )
        // 显示天气数据
        binding.detailTodayCard.apply {
            // 最高和最低温
            tvTemperature.text = "${weatherDaily.tempMin}° / ${weatherDaily.tempMax}°"
            // 白天天气 夜间天气 月相
            weatherMoonPhase.apply {
                tvName1.text = "白天天气"
                tvValue1.text = weatherDaily.textDay
                tvName2.text = "夜间天气"
                tvValue2.text = weatherDaily.textNight
                tvName3.text = "月相"
                tvValue3.text = weatherDaily.moonPhase
                val iconDay = "_${weatherDaily.iconDay.replace("-", "_")}"
                val iconNight = "_${weatherDaily.iconNight.replace("-", "_")}"
                val iconMoon = "_${weatherDaily.moonPhaseIcon.replace("-", "_")}"
                ivIcon1.apply {
                    setImageDrawable(getIconDrawable(iconDay))
                    visibility = View.VISIBLE
                }
                ivIcon2.apply {
                    setImageDrawable(getIconDrawable(iconNight))
                    visibility = View.VISIBLE
                }
                ivIcon3.apply {
                    setImageDrawable(getIconDrawable(iconMoon))
                    visibility = View.VISIBLE
                }
            }
            // 湿度 紫外线 气压
            humidityUvPressure.apply {
                tvName1.text = "湿度"
                tvName2.text = "紫外线强度指数"
                tvName3.text = "气压"
                tvValue1.text = weatherDaily.humidity
                tvValue2.text = weatherDaily.uvIndex
                tvValue3.text = "${weatherDaily.pressure}hPa"
            }
            // 日降水量和能见度
            rainVisContainer.apply {
                tvName1.text = "日降水量"
                tvName2.text = "能见度"
                tvValue1.text = "${weatherDaily.precip} mm"
                tvValue2.text = "${weatherDaily.vis}km"
            }
            // 日出 日落
            tvSunriseSunset.text =
                "日出时间：${weatherDaily.sunrise} 日落时间：${weatherDaily.sunset}"
            // 月出 月落
            tvMoonriseMoonset.text =
                "月出时间：${weatherDaily.moonrise} 月落时间：${weatherDaily.moonset}"
            // 风况
            tvDayWindNightWind.text =
                "白天风：${weatherDaily.windSpeedDay}km/h 夜间风：${weatherDaily.windSpeedNight}km/h"
        }
    }

    override fun getWeather3dayDataFailed(message: String) {

    }

    override fun onPause() {
        super.onPause()
        if (isStar) {
            CityStarUtils.addCityStar(cityStar!!)
        } else {
            CityStarUtils.removeCityStar(currentCity!!.cityName)
        }
    }

    @SuppressLint("UseCompatLoadingForDrawables", "DiscouragedApi")
    fun getIconDrawable(icon: String): Drawable? {
        val iconId = this.resources.getIdentifier(icon, "drawable", this.packageName)
        return this.resources.getDrawable(iconId, null)
    }

    fun initCityStar() {
        val starBtn = binding.detailTodayCard.ivDetailStarCity
        // 绑定监听事件
        starBtn.setOnClickListener {
            operaCityStar(starBtn)
        }
        // 1. 先从意图里取
//        isStar = intent.getBooleanExtra("isStar", false)
//        if (isStar) {
//            starBtn.setImageResource(R.mipmap.icon_stared)
//            return
//        }
        // 2. 从首选项里取
        if (CityStarUtils.getCurrentCity(currentCity!!.cityName)) {
            isStar = true
            starBtn.setImageResource(R.mipmap.icon_stared)
            return
        }
        // 3. 默认
        starBtn.setImageResource(R.mipmap.icon_detail_star)
    }

    fun operaCityStar(view: ImageView) {
        if (isStar) {
            view.setImageResource(R.mipmap.icon_detail_star)
        } else {
            view.setImageResource(R.mipmap.icon_stared)
        }
        isStar = !isStar
    }
}